package com.wecheir.controller;


import com.wecheir.dao.UserDao;
import com.wecheir.entity.LoginData;
import com.wecheir.entity.User;
import com.wecheir.entity.UserRegister;
import com.wecheir.service.LoginDataService;
import com.wecheir.service.UserService;
import com.wecheir.utils.Constants;
import com.wecheir.utils.ResponseUtils;
import com.wecheir.utils.UploadUtil;
import com.wecheir.utils.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping( "/app" )
public class UserController {

    @Resource
    UserService userService;

    @Resource
    LoginDataService loginDataService;

    @Resource
    UserDao userDao;

    private LoginData loginDataNew=new LoginData();//登录成功后的数据

    private LoginData loginDataLast=new LoginData();//登录没成功，上一次登录成功的数据


    @GetMapping("/index")
    public String index(){
        System.out.println("index");
        return "index";
    }

    /**
     * 登录用户
     * @param userParam
     * @param roleId
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResponseUtils login(User userParam,@RequestParam(value = "roleId",required = false)String roleId){

        if (!UserUtil.userCoverEmailOrTell(userParam)){
            return ResponseUtils.setFailure("你输入的属性中没有电话号码或者邮箱,请重新输入!");
        }

        User user = userDao.selectUserByUser(userParam);

        System.out.println("userParam = "+userParam.toString());
        System.out.println("user = "+user.toString());

        ResponseUtils responseUtils = userService.checkUser(userParam,user);
        if (responseUtils.getCode() == ResponseUtils.CODE_SUCCESS){
            loginDataService.addLoginData(user);
        }
        return responseUtils;
    }


    /**
     * 注册用户
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public ResponseUtils  register(UserRegister user, HttpServletRequest request) {
        String loginName = request.getParameter("loginName");
        String tel = request.getParameter("tel");
        String email = request.getParameter("email");
        String identity = request.getParameter("identity");
        String requestPlace = request.getParameter("requestPlace");
        String age = request.getParameter("age");
        HttpSession session = request.getSession();
        System.out.println("sessionId"+session.getId());
        if (StringUtils.isBlank(loginName)) {
            return ResponseUtils.setFailure("昵称不能为空");
        } else if (StringUtils.isBlank(tel)) {
            return ResponseUtils.setFailure("手机号码不能为空");
        } else if (StringUtils.isBlank(email)) {
            return ResponseUtils.setFailure("邮箱不能为空");
        } else if (StringUtils.isBlank(identity)) {
            return ResponseUtils.setFailure("身份不能为空");
        } else if (StringUtils.isBlank(requestPlace)) {
            return ResponseUtils.setFailure("常用请求地址不能为空");
        } else if (StringUtils.isBlank(age)) {
            return ResponseUtils.setFailure("年龄不能为空");
        }else if (Integer.parseInt(age)-18<0) {
            return ResponseUtils.setFailure("年龄必须在18--60岁之间");
        }else if (60-Integer.parseInt(age)<0) {
            return ResponseUtils.setFailure("年龄必须在18--60岁之间");
        }

        //查询登录名是否重复
        if(userDao.findUserByLoginName(loginName).size() > 0){
            System.out.println("用户名重复");
            return ResponseUtils.setFailure("用户名重复");
        };

        //保存用户操作
        user.setLoginName(loginName);
        user.setPassword(Constants.PASS_WORLD);
        user.setSalt(Constants.SALT);
        user.setAdminUser(true);
        user.setLocked(false);
        user.setId(session.getId());
        try {
            userDao.userRegister(user);
            if (StringUtils.isBlank(user.getId())) {
                System.out.println("Failure");
                return ResponseUtils.setFailure("保存用户信息出错");
            }
            return ResponseUtils.setSuccess(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("注册失败,请重试!");
        return ResponseUtils.setFailure("注册失败,请重试!");
    }


    /**
     * 更新用户部分
     */
    @PostMapping("/updateLoginName")
    @ResponseBody
    public ResponseUtils updateLoginName(String id,String loginName){
        if(!userDao.updateLoginNameById(id,loginName)){
            return ResponseUtils.setFailure("更新失败");
        }
        return ResponseUtils.setSuccess("");
    }

    @PostMapping("/updateNickName")
    @ResponseBody
    public ResponseUtils updateNickName(String id,String nickName){
        if(!userDao.updateNickNameById(id,nickName)){
            return ResponseUtils.setFailure("更新失败");
        }
        return ResponseUtils.setSuccess("");
    }

    @PostMapping("/updateRemarks")
    @ResponseBody
    public ResponseUtils updateRemarks(String id,String remarks){
        if(!userDao.updateRemarksById(id,remarks)){
            return ResponseUtils.setFailure("更新失败");
        }
        return ResponseUtils.setSuccess("");
    }

    @PostMapping("/uploadIcon")
    @ResponseBody
    public ResponseUtils uploadIcon(String id, MultipartFile icon){
        String originalFilename = icon.getOriginalFilename();
        File uploadDir = new File(UploadUtil.basePath);
        if (!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        String fileName = UploadUtil.getFileName(originalFilename);
        try {
            icon.transferTo(new File(UploadUtil.basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseUtils.setFailure("文件存储失败");
        }
        String path =  UploadUtil.getPath(fileName);

        if(!userDao.updateIconById(id,path)){
            return ResponseUtils.setFailure("更新失败");
        }
        return ResponseUtils.setSuccess( path );
    }


    @PostMapping("/alertPwd")
    @ResponseBody
    public ResponseUtils alertPwd(String userName,String oldPwd,String newPwd){
        User user = userDao.findUserByName(userName);
        if (!oldPwd.equals(user.getPassword())){
            return ResponseUtils.setFailure("原始密码错误！");
        }
        userDao.updatePwd(userName,newPwd);
        return ResponseUtils.setSuccess("");
    }

}
